using System.Linq.Expressions;
using Shard.Contracts;
using Shared.SqlSugarCore;
using Shared.SqlSugarCore.Repository;
using SqlSugar;
using UserService.Domain.Entities;
using Volo.Abp.Domain.Repositories;

namespace UserService.SqlSugarCore.Repositories;

/// <summary>
/// 用户仓储实现
/// </summary>
public class UserRepository(ISqlSugarClient sqlSugarClient) : SqlSugarRepository<UserAggregateRoot, Guid>(sqlSugarClient)
{
    private readonly ISqlSugarClient _sqlSugarClient = sqlSugarClient;

    /// <summary>
    /// 根据条件查询单个用户
    /// </summary>
    public async Task<UserAggregateRoot> FirstOrDefaultAsync(Expression<Func<UserAggregateRoot, bool>> predicate)
    {
        return await _sqlSugarClient.Queryable<UserAggregateRoot>()
            .FirstAsync(predicate);
    }
        
    /// <summary>
    /// 分页查询用户列表
    /// </summary>
    public async Task<(List<UserAggregateRoot> Items, long TotalCount)> GetPagedListAsync(
        int skipCount, 
        int maxResultCount, 
        Expression<Func<UserAggregateRoot, bool>> predicate = null)
    {
        var query = _sqlSugarClient.Queryable<UserAggregateRoot>();
            
        if (predicate != null)
        {
            query = query.Where(predicate);
        }
            
        var total = await query.CountAsync();
        var items = await query
            .Skip(skipCount)
            .Take(maxResultCount)
            .ToListAsync();
                
        return (items, total);
    }
}